<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id="app">
    <h3>购物车</h3>
    <ul>
      <li
        v-for="product in cart"
      >
        {{ product.id }} - {{ product.title }} - {{ product.price }} - 
        <button v-on:click="handleModifyAmount('minus', product)">-</button>
        {{ product.amount }}
        <button v-on:click="handleModifyAmount('plus', product)">+</button>
        - {{ (product.price * product.amount).toFixed(2) }}
        - <button v-on:click="handleRemove(product.id)">删除</button>
      </li>
    </ul>
    <div>合计：{{ total }}</div>
  
    <h3>推荐</h3>
    <ul>
      <li
        v-for="product in products"
      >
        {{ product.id }} - {{ product.title }} -- {{ product.price }}
        - <button v-on:click="handleAddToCart(product)">加入购物车</button>
      </li>
    </ul>
  </div>

  <script src="./libs/vue.js"></script>
  <script>
    const _products = new Array(8).fill(null).map((v, i) => ({
      id: i + 1,
      title: '商品标题' + (i + 1),
      price: (Math.random() * 100).toFixed(2)
    }))

    const vm = new Vue({
      el: '#app', // view，element
      data: { // model
        products: _products, // 推荐商品数组
        cart: [], // 购物车数组
      },
      computed: { // 计算属性
        total() {
          return (this.cart.reduce((result, curr) => result + curr.amount * curr.price, 0)).toFixed(2)
        }
      },
      methods: {
        /**
         * 加入购物车
         */
        handleAddToCart(prod) {
          // 当前选购商品
          const currentProduct = {
            ...prod,
            amount: 1
          }
          // 查找购物车中已存在的当前选购商品对象
          const existProduct = this.cart.find(item => item.id === prod.id)
          // 如果已存在，则叠加选购商品的数量即可，不存在，则添加到购物车数组中
          if (existProduct) {
            existProduct.amount += currentProduct.amount
          } else {
            this.cart.push(currentProduct)
          }
        },
        /**
         * 修改数量
         */
        handleModifyAmount(type, product) {
          if (type === 'minus') { // 减数量
            if (product.amount <= 1) {
              return
            }
            product.amount -= 1
          } else if (type === 'plus') { // 加数量
            product.amount += 1
          }
        },
        /**
         * 删除购物车商品
         */
        handleRemove(id) {
          this.cart = this.cart.filter(item => item.id !== id)
        },
      }
    })
  </script>
</body>
</html>